<template>
  <div class="income-total">
    <div class="page-header">
      <h2>收入统计</h2>
      <p>平台收入数据统计与分析</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">¥{{ totalIncome }}</div>
            <div class="stat-label">平台总收入</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pendingCount }}</div>
            <div class="stat-label">待结算收入</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon settled">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ settledCount }}</div>
            <div class="stat-label">已结算收入</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon platform">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">3%</div>
            <div class="stat-label">平台费率</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 收入类型统计 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>收入类型分布</span>
        </div>
      </template>
      
      <div class="income-types">
        <div class="type-item">
          <div class="type-info">
            <el-tag type="info">发布费</el-tag>
            <span class="type-amount">¥{{ publishFeeTotal }}</span>
          </div>
          <div class="type-count">{{ publishFeeCount }} 笔</div>
        </div>
        
        <div class="type-item">
          <div class="type-info">
            <el-tag type="success">完成费</el-tag>
            <span class="type-amount">¥{{ completeFeeTotal }}</span>
          </div>
          <div class="type-count">{{ completeFeeCount }} 笔</div>
        </div>
        
        <div class="type-item">
          <div class="type-info">
            <el-tag type="warning">平台费</el-tag>
            <span class="type-amount">¥{{ platformFeeTotal }}</span>
          </div>
          <div class="type-count">{{ platformFeeCount }} 笔</div>
        </div>
      </div>
    </el-card>

    <!-- 最近收入记录 -->
    <el-card class="recent-card">
      <template #header>
        <div class="card-header">
          <span>最近收入记录</span>
          <el-button type="primary" size="small" @click="refreshData">刷新数据</el-button>
        </div>
      </template>
      
      <el-table :data="recentIncomes" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="taskTitle" label="任务标题" min-width="150" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'">
              {{ row.status === 1 ? '已结算' : '待结算' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getTotalIncome, getPendingIncome, getSettledIncome } from '../../utils/api'

const loading = ref(false)
const totalIncome = ref('0.00')
const pendingCount = ref(0)
const settledCount = ref(0)
const recentIncomes = ref([])

// 收入类型统计
const publishFeeTotal = ref('0.00')
const completeFeeTotal = ref('0.00')
const platformFeeTotal = ref('0.00')
const publishFeeCount = ref(0)
const completeFeeCount = ref(0)
const platformFeeCount = ref(0)

// 获取总收入
const loadTotalIncome = async () => {
  try {
    console.log('开始获取总收入...')
    const response = await getTotalIncome()
    console.log('总收入API响应:', response)
    if (response.data && response.data.code === 200) {
      totalIncome.value = response.data.data || '0.00'
      console.log('总收入数据:', totalIncome.value)
    } else {
      console.error('总收入API返回错误:', response.data?.message)
    }
  } catch (error) {
    console.error('获取总收入失败:', error)
  }
}

// 获取待结算收入数量
const loadPendingCount = async () => {
  try {
    const response = await getPendingIncome()
    if (response.data && response.data.code === 200) {
      pendingCount.value = response.data.data.length
      // 统计各类型收入
      calculateIncomeStats(response.data.data, 'pending')
    }
  } catch (error) {
    console.error('获取待结算收入失败:', error)
  }
}

// 获取已结算收入数量
const loadSettledCount = async () => {
  try {
    const response = await getSettledIncome()
    if (response.data && response.data.code === 200) {
      settledCount.value = response.data.data.length
      // 统计各类型收入
      calculateIncomeStats(response.data.data, 'settled')
      // 设置最近收入记录
      recentIncomes.value = response.data.data.slice(0, 10)
    }
  } catch (error) {
    console.error('获取已结算收入失败:', error)
  }
}

// 计算收入统计
const calculateIncomeStats = (incomes, type) => {
  incomes.forEach(income => {
    const amount = parseFloat(income.amount) || 0
    switch (income.type) {
      case 1: // 发布费
        if (type === 'settled') {
          publishFeeTotal.value = (parseFloat(publishFeeTotal.value) + amount).toFixed(2)
          publishFeeCount.value++
        }
        break
      case 2: // 完成费
        if (type === 'settled') {
          completeFeeTotal.value = (parseFloat(completeFeeTotal.value) + amount).toFixed(2)
          completeFeeCount.value++
        }
        break
      case 3: // 平台费
        if (type === 'settled') {
          platformFeeTotal.value = (parseFloat(platformFeeTotal.value) + amount).toFixed(2)
          platformFeeCount.value++
        }
        break
    }
  })
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '发布费',
    2: '完成费',
    3: '平台费'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'info',
    2: 'success',
    3: 'warning'
  }
  return typeMap[type] || 'info'
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadTotalIncome(),
      loadPendingCount(),
      loadSettledCount()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.income-total {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.settled {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.platform {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.chart-card, .recent-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.income-types {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.type-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.type-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.type-amount {
  font-size: 16px;
  font-weight: bold;
  color: #67c23a;
}

.type-count {
  font-size: 14px;
  color: #909399;
}

.amount {
  color: #67c23a;
  font-weight: bold;
}
</style>
